package com.hmtech.ayp.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmtech.ayp.domain.entity.Category;
import com.hmtech.ayp.domain.entity.Style;
import com.hmtech.ayp.domain.entity.StyleCategory;
import com.hmtech.ayp.domain.vo.CategoryVO;
import com.hmtech.ayp.enums.CommonState;
import com.hmtech.ayp.enums.DeletedFlag;
import com.hmtech.ayp.mapper.CategoryMapper;
import com.hmtech.ayp.service.ICategoryService;
import com.hmtech.ayp.service.IStyleCategoryService;
import com.hmtech.ayp.service.IStyleService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@AllArgsConstructor(onConstructor = @__(@Autowired))
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>
        implements ICategoryService {

    @Override
    public List<CategoryVO> listAll(boolean withStyles) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<Category>()
                .eq(Category::getStatus, CommonState.ENABLED.value)
                .eq(Category::getDeleted, DeletedFlag.NOT_DELETED.value);
        List<Category> categories = list(queryWrapper);
        if (!withStyles) {
            return convertWithoutStyles(categories);
        }
        List<CategoryVO> list = baseMapper.listAllWithStyles();
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.stream().filter(categoryVO -> CollectionUtil.isNotEmpty(categoryVO.getStyles()))
                .collect(Collectors.toList());
    }

    private List<CategoryVO> convertWithoutStyles(List<Category> categories) {
        if (CollectionUtil.isEmpty(categories)) {
            return null;
        }
        return categories.stream()
                .map(category -> new CategoryVO(category.getTitle()))
                .collect(Collectors.toList());
    }
}
